<?php


namespace App\Http\Server;


use App\Models\User;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class LoginServer
{
    //token 有效期
    const TOKEN_EXPIRE = 3600*24*3;
    //连接Redis
    static function redisConnection(){
        return Redis::connection("user_token")->client();
    }
    //重置用户Token数据
    static function resetUserTokenValue($token,$data){
        $redis = self::redisConnection();
        $redis->setex($token,self::TOKEN_EXPIRE,json_encode($data,JSON_UNESCAPED_UNICODE));
    }
    //重置token有效期
    static function resetUserTokenExpire($token){
        return self::redisConnection()->expire($token,self::TOKEN_EXPIRE);
    }
    //删除redis token
    static function removeToken($token){
        return self::redisConnection()->del($token);
    }
    //根据token从redis获取用户信息
    static function getUserInfoForToken($token){
        return json_decode(self::redisConnection()->get($token),true);
    }

    public function loginServer($code)
    {
        $config = (new WechatServer())->config();
        $app = Factory::miniProgram($config);
        try {
            // 使用 code 换取 session_key 和 openid
            $result = $app->auth->session($code);
            if (isset($result['errcode'])) {
                return [
                    'code' => 201,
                    'data' => [],
                    'msg' => $result['errmsg']
                ];
            }
            $user = User::where('openid',$result['openid'])->first();
            if($user){
                $token = $user->token;
                //判断token是否过期
                $users = self::getUserInfoForToken($token);
                if($users){
                    self::resetUserTokenExpire($token);
                }else{
                    // 生成并返回 token
                    $token = md5($result['openid'].uniqid());
                    User::where('openid',$result['openid'])->update(['token'=>$token]);
                    $user = User::where('openid',$result['openid'])->first()->toArray();
                    $user  = (array)$user;
                }
            }else{
                // 生成并返回 token
                $token = md5($result['openid'].uniqid());
                User::insert(
                    [
                        'openid'=>$result['openid'],
                        'session_key'=>$result['session_key'],
                        'token'=>$token
                    ]);
                $user = User::where('openid',$result['openid'])->first()->toArray();
                $user  = (array)$user;
            }
            self::resetUserTokenValue($token,$user);
            return [
                'code' => 200,
                'data' => [
                    'openid' => $result['openid'],
                    'session_key' => $result['session_key'],
                    'userinfo'=>$user,
                    'token'=>$token
                ],
                'msg' => 'success'
            ];
        } catch (\Exception $e) {
            return [
                'code' => 201,
                'data' => [],
                'msg' => $e->getMessage()
            ];
        }

    }
    public function getUserInfoByToken($token){
        return json_decode(self::redisConnection()->get($token),true);
    }

}
